package com.itheima.handler;

import com.itheima.exception.BaseException;
import com.itheima.pojo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /*@ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error("系统发生异常:{}",e.getMessage());
        e.printStackTrace();
        return Result.error("系统发生错误，请稍后再试~");
    }*/

    @ExceptionHandler(BaseException.class)
    public Result baseExceptionHandler(BaseException be) {
        log.error("发生业务异常:{}",be.getMessage());
        be.printStackTrace();
        return Result.error(be.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        //Column 'clazz_id' cannot be null
        String msg = ex.getMessage();
        if(msg.contains("cannot be null")){
            String[] split = msg.split(" ");
            if(split[1].contains("clazz_id")){
                return Result.error("班级不能为空！");
            }
        }
        return Result.error("系统发生错误，请稍后再试~");
    }
}
